import React, { Component } from 'react';
import {
	StyleSheet, View, Text, PixelRatio,
	Image, TouchableOpacity, FlatList, DeviceEventEmitter
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;

let pageNo = 1;
let totalPage = 0;

export class MyPlanPage extends Component {

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '经营计划',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.yearData = [
			{ title: '2020' },
			{ title: '2019' },
			{ title: '2018' },
			{ title: '2017' },
			{ title: '2016' }
		];
		this.monthData = [
			{ title: '12' },
			{ title: '11' },
			{ title: '10' },
			{ title: '9' },
			{ title: '8' }
		]
		this.state = {
			dataArray: [],   //数据
			yearModalVisible: false, //  顶部下拉 -年
			yearIndex: 0,  // 选中字段 -年
			yearValue: this.yearData[0].title,  // 年 字段
			monthValue: this.monthData[0].title,  // 月 字段
			monthIndex: 0, // 选中字段 -年
			onoff: true,  // true -> 年    false - > 月
			pageStatus: {
				status: 'loading'
			},
			loadIcon: false,  // 下拉涮新的 图标
		}
	}

	//初始化数据
	componentWillMount () {
		this._getData();
	}

	componentDidMount () {
		DeviceEventEmitter.addListener('passByValue', (res) => {
			this._getData()
		});
	}


	//获取页面
	async _getData (sendData) {
		this.setState({
			loadIcon: true,
		})
		let options = sendData || { onrefresh: true, pageNo, totalPage };
		let responseData = await HTTP.POST(API_GENERATE(API.MY_PLAN_LIST), options);

		this.setState({
			loadIcon: false
		});

		if (responseData && responseData.planPageModel.rows.length) {
			totalPage = responseData.planPageModel.totalPage;
			if (options.onrefresh) {  // 刷新
				this.setState({
					pageStatus: {
						status: 'data'
					},
					dataArray: responseData.planPageModel.rows,
					recordCount: responseData.planPageModel.recordCount,
					nowList: responseData.planPageModel.rows.length
				});
			} else {  ///加载
				this.setState({
					pageStatus: {
						status: 'data'
					},
					dataArray: this.state.dataArray.concat(responseData.planPageModel.rows),
					recordCount: responseData.planPageModel.recordCount,
					nowList: this.state.nowList + responseData.planPageModel.rows.length
				})
			}
		} else {
			this.setState({
				pageStatus: {
					status: 'empty',
					emptyText: '还没有计划哦~'
				}
			})
		}

	}

	// 下拉更新函数
	_isLoadRefresh () {
		this._getData();
	}

	//加载更过
	_loadData () {
		if (totalPage > pageNo) {
			pageNo++;
			this._getData({
				pageNo,
				onrefresh: false
			});
		}
	}
	//新增按钮
	_callBack = () => {
		this.props.navigation.navigate('AddMyPlanPage');
	}

	//一条数据
	_renderItem (data) {
		let { productName, planQuantity, title, updateTime, planPrice, planId, status } = data.item;
		return (
			<TouchableOpacity style={styles.listItem} onPress={() => {
				const { navigate } = this.props.navigation;
				/* navigate('MyPlanDetailPage', {
					planId
				}); */
			}} activeOpacity={0.5}>
				<View style={styles.listHead}>
					<Text style={styles.listLeftText}>{title}</Text>
					<Text style={styles.listRightText}>{status}</Text>
				</View>
				<View style={styles.listBody}>
					<View style={styles.listLine}>
						<Text style={styles.listText}>商品：{productName}</Text>
						<Text style={styles.listText}>计划量：{planQuantity}</Text>
					</View>
					<View style={styles.listLine}>
						<Text style={styles.listText}>预测价格：<Text style={styles.listTheme}>￥{this.simpleFormatAsMoney(planPrice)}</Text></Text>
						<Text style={styles.listText}>提交时间:{this._getTimeStr(updateTime)}</Text>
					</View>
				</View>
			</TouchableOpacity>
		)
	}

	_getTimeStr (str) {
		if (str && str.length) {
			const currDate = new Date(str.replace(/-/g, '/'));
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate(),
				h = currDate.getHours(),
				mi = currDate.getMinutes();
			let dateStr = "";
			dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + (h < 10 ? "0" + h : h) + ":" + (mi < 10 ? "0" + mi : mi);
			return dateStr;
		} else {
			return null;
		}
	}

	simpleFormatAsMoney (mnt) {
		mnt -= 0;
		mnt = (Math.round(mnt * 100)) / 100;
		return (mnt == Math.floor(mnt)) ? mnt + '.00' : ((mnt * 10 == Math.floor(mnt * 10)) ? mnt + '0' : mnt);
	}

	render () {
		let { yearModalVisible, yearValue, monthValue, pageStatus } = this.state;
		return (
			<View style={styles.container}>
				{
					pageStatus.status === 'data' ?
						<View style={{ marginBottom: 65 * scale, flex: 1 }}>
							{/* <View style={styles.timeBox}>
								<TouchableOpacity onPress={() => { this._yearVisible(true) }} style={styles.timeItem}>
									<Text style={styles.timeText}>{yearValue}年</Text>
									<Image style={styles.timeImg} source={require('../../../imgs/Group.png')} />
								</TouchableOpacity>
								<TouchableOpacity onPress={() => { this._yearVisible(false) }} style={styles.timeItem}>
									<Text style={styles.timeText}>{monthValue}月</Text>
									<Image style={styles.timeImg} source={require('../../../imgs/Group.png')} />
								</TouchableOpacity>
							</View> */}

							<View style={styles.listBox}>
								<FlatList
									data={this.state.dataArray}
									renderItem={(data) => this._renderItem(data)}
									refreshing={this.state.loadIcon}
									onRefresh={this._isLoadRefresh.bind(this)}
									onEndReachedThreshold={1}
									onEndReached={() => { this._loadData() }}
								/>
							</View>
						</View>
						: <View style={{ flex: 1 }}>
							<PageStatusIndex {...pageStatus} />
						</View>
				}

				<Common type="bottom" title="添加" callBack={this._callBack} />
				{yearModalVisible ? this._modalYear() : null}
			</View>
		)
	}



	//底部弹框模板  - 年
	_modalYear () {
		let { yearIndex, onoff, monthIndex } = this.state;
		return (
			/* 头部弹框 */
			<Common styleOut={styles.BombOut} allClick={this._allVisible} styleBox={styles.BombBox} data={onoff ? this.yearData : this.monthData} itemFn={this._yearItem} imgIndex={onoff ? yearIndex : monthIndex} type="selectModal" />
		)
	}

	//点击其它地方隐藏
	_allVisible = () => {
		this.setState({
			yearModalVisible: false
		})
	}
	// 弹框显示隐藏控制
	_yearVisible = (str) => {

		let { onoff, yearModalVisible } = this.state;

		if (str) {   // str 年
			if (onoff && yearModalVisible) {
				this.setState({
					yearModalVisible: false
				})
			} else {
				this.setState({
					yearModalVisible: true,
					onoff: true
				})
			}
		} else {   // 月
			if (!onoff && yearModalVisible) {
				this.setState({
					yearModalVisible: false
				})
			} else {
				this.setState({
					yearModalVisible: true,
					onoff: false
				})
			}
		}




		return;


		this.setState({
			onoff: str,
		}, function () {
			if (this.state.onoff && this.setState.yearModalVisible) {
				this.setState({
					yearModalVisible: false
				})
			} else {
				this.setState({
					yearModalVisible: true
				})
			}
		})

	}

	// 点击每条栏目的事件
	_yearItem = (sendObj) => {
		this._allVisible();
		if (this.state.onoff) {  // 年
			this.setState({
				yearIndex: sendObj.index,
				yearValue: sendObj.item.title
			})
		} else {  //月
			this.setState({
				monthIndex: sendObj.index,
				monthValue: sendObj.item.title
			})
		}

	}


}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	timeBox: {
		height: 45 * scale,
		position: 'absolute',
		top: 0,
		backgroundColor: style.color.white,
		flexDirection: 'row',
		alignItems: 'center',
	},
	timeItem: {
		width: '50%',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	timeImg: {
		tintColor: style.color.dark,
		marginLeft: 15 * scale
	},
	timeText: {
		color: style.color.normal,
		fontSize: 14 * scale,
	},
	listBox: {
		//	marginTop: 45 * scale
	},
	listItem: {
		backgroundColor: style.color.white,
		marginTop: 12 * scale,
	},
	listHead: {
		height: 42 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		backgroundColor: style.color.white,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		paddingLeft: 13 * scale,
		paddingRight: 13 * scale
	},
	listLeftText: {
		fontSize: 13 * scale,
		color: style.color.normal
	},
	listRightText: {
		fontSize: 12 * scale,
		color: style.color.themeColor
	},
	listBody: {
		paddingLeft: 13 * scale,
		paddingRight: 13 * scale,
		backgroundColor: style.color.white,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale
	},
	listText: {
		fontSize: 13 * scale,
		color: style.color.normal,
		lineHeight: 34 * scale,
		width: '50%'
	},
	listLine: {
		flexDirection: 'row'
	},
	listTheme: {
		color: style.color.themeColor
	},
	BombOut: {
		top: 45 * scale
	}

})